package com.rabbiter.market.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathUtils {

    private static final Logger logger = LoggerFactory.getLogger(PathUtils.class);

    private static final String FILE_PATH = "/app/supermarket/file/img/";

    public static String getClassLoadRootPath() {
        String path = "";
        String prePath = null;
        try {
            prePath = URLDecoder.decode(PathUtils.class.getClassLoader().getResource("").getPath(),"utf-8").replace("/target/classes", "");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().startsWith("mac")) {
            // 苹果
            path = prePath.substring(0, prePath.length() - 1);
        } else if (osName.toLowerCase().startsWith("windows")) {
            // windows
            path = prePath.substring(1, prePath.length() - 1);
        } else if(osName.toLowerCase().startsWith("linux") || osName.toLowerCase().startsWith("unix")) {
            // unix or linux
            path = prePath.substring(0, prePath.length() - 1);
        } else {
            path = prePath.substring(1, prePath.length() - 1);
        }
        return path;
    }

    public static String upload(MultipartFile multipartFile) {
        String res = null;  // 返回网络路径
        try {
//            String staticDir = PathUtils.getClassLoadRootPath();
            Path path = Paths.get(FILE_PATH);

            // 如果结果目录不存在，则创建目录
            if(!Files.exists(path)) {
                Files.createDirectories(path);
            }

            // 创建文件对象
            // 构建目标路径
            Path uploadPath = path.toAbsolutePath().normalize();

            // 加个时间戳防止重名
            String fileName = System.currentTimeMillis() + "_" + multipartFile.getOriginalFilename();

            Path filePath = uploadPath.resolve(fileName);

            // 保存文件
            multipartFile.transferTo(filePath.toFile());

            res = "/file/img/" + fileName;
        } catch (Exception e) {
           logger.info("上传文件失败", e);
        }
        return res;
    }

}
